package com.zhonghui.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhonghui.common.core.utils.RedisUtils;
import com.zhonghui.common.core.exception.DataOrCheckException;
import com.zhonghui.common.core.result.FwResult;
import com.zhonghui.dto.*;
import com.zhonghui.mapper.AddressMapper;
import com.zhonghui.mapper.OrderMapper;
import com.zhonghui.mapper.ProductMapper;
import com.zhonghui.mapper.UserMapper;
import com.zhonghui.model.*;
import com.zhonghui.service.OrderService;
import com.zhonghui.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author: FL
 * @create: 2024 2024/5/5 13:02
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserMapper userMapper;
    /**
     * 根据订单号查询订单(获取订单详情)
     * @param orderNo
     * @return
     */
    @Override
    public FwResult getOrderByOrderNo(String orderNo) {
        Long userId = Long.valueOf(redisUtils.get("userId"));
        List<OrderDetail> details = orderMapper.getOrderByOrderNo(userId, orderNo);
        OrderInfo orderInfo = orderMapper.getOrderInfoByOrderNo(userId, orderNo).get(0);


        if (details.isEmpty()){
            log.warn("订单不存在");
            return FwResult.failedMsg("订单不存在");
        }

        List<ProductInOrder> productInOrders = new ArrayList<>();
        BigDecimal totalPrice = BigDecimal.ZERO;
        Long totalNum = 0L;
        for (OrderDetail detail : details) {
            Product product = productMapper.getProduct(detail.getProductId());
            // 修正总价计算，使用add()方法的返回值
            totalPrice = totalPrice.add(detail.getCurrentUnitPrice().multiply(new BigDecimal(detail.getQuantity())));
            totalNum = totalNum + detail.getQuantity();
            ProductInOrder productInOrder = ProductInOrder.builder()
                    .productName(product.getName())
                    .productImage(product.getMainImage())
                    .productPrice(product.getPrice())
                    .productNum(detail.getQuantity())
                    .productTotalPrice(detail.getCurrentUnitPrice().multiply(new BigDecimal(detail.getQuantity())))
                    .build();
            productInOrders.add(productInOrder);
        }

        OrderDetailVo detailVo = OrderDetailVo.builder()
                .orderNo(details.get(0).getOrderNo())
                .receiveName(orderInfo.getReceiveName())
                .products(productInOrders)
                .totalPrice(totalPrice)
                .totalNum(totalNum)
                .statusDesc(details.get(0).getStatusDesc())
                .id(details.get(0).getId())
                .createTime(details.get(0).getCreateTime())
                .build();
        return FwResult.ok(detailVo);
    }

//        @Override
//        public FwResult getOrderByOrderNo(String orderNo) {
//            Long userId = Long.valueOf(redisUtils.get("userId"));
//            // 查询订单信息
//            List<OrderInfo> orderInfoList = orderMapper.getOrderInfoByOrderNo(userId, orderNo);
//            // 查询订单详情
//            List<OrderDetail> details = orderMapper.getOrderByOrderNo(userId, orderNo);
//
//
//
//
//            if (orderInfoList.isEmpty() || details.isEmpty()) {
//                return FwResult.failedMsg("订单信息不存在");
//            }
//
//            List<OrderDetailVo> orderDetailVos = new ArrayList<>();
//
//            // 遍历每个订单信息
//            for (OrderInfo orderInfo : orderInfoList) {
//                BigDecimal totalPrice = BigDecimal.ZERO;
//                Long totalNum = 0L;
//                List<ProductInOrder> productInOrders = new ArrayList<>();
//
//                // 遍历订单详情并计算总价、总数量等
//                for (OrderDetail detail : details) {
//                    if (detail.getOrderNo().equals(orderInfo.getOrderNo())) { // 匹配订单号
//                        Product product = productMapper.getProduct(detail.getProductId());
//                        totalPrice = totalPrice.add(detail.getCurrentUnitPrice().multiply(new BigDecimal(detail.getQuantity())));
//                        totalNum += detail.getQuantity();
//
//                        // 构建商品信息
//                        ProductInOrder productInOrder = ProductInOrder.builder()
//                                .productName(product.getName())
//                                .productImage(product.getMainImage())
//                                .productPrice(product.getPrice())
//                                .productNum(detail.getQuantity())
//                                .productTotalPrice(detail.getCurrentUnitPrice().multiply(new BigDecimal(detail.getQuantity())))
//                                .build();
//                        productInOrders.add(productInOrder);
//                    }
//                }
//
//                // 构建订单详情VO
//                OrderDetailVo detailVo = OrderDetailVo.builder()
//                        .orderNo(orderInfo.getOrderNo())
//                        .receiveName(orderInfo.getReceiveName())
//                        .products(productInOrders)
//                        .totalPrice(totalPrice)
//                        .totalNum(totalNum)
//                        .statusDesc(orderInfo.getStatusDesc())
//                        .id(orderInfo.getId())
//                        .createTime(orderInfo.getCreateTime())
//                        .build();
//
//                orderDetailVos.add(detailVo);
//            }
//
//            return FwResult.ok(orderDetailVos); // 返回多个订单详情
//        }




    @Override
    public FwResult getOrderPage(PageDto pageDto) {
        Long userId = Long.valueOf(redisUtils.get("userId"));
        PageHelper.startPage(pageDto.getCurrent(), pageDto.getSize());
        List<OrderDetail> details = orderMapper.getOrderPage(userId);
        log.info("订单详情：{}",details);
        PageInfo<OrderDetail> pageInfo = new PageInfo<>(details);
        if (details.isEmpty()){
            return FwResult.failedMsg("没有订单");
        }

        Map<String, OrderDetailVo> orderVoMap = new HashMap<>();
        for (OrderDetail detail : details) {
            // 使用订单号作为键，避免重复添加
            OrderDetailVo vo = orderVoMap.computeIfAbsent(detail.getOrderNo(), k -> {
                OrderInfo orderInfo = orderMapper.getOrderInfoByOrderNo(userId, detail.getOrderNo()).get(0);
                // 如果该订单号还没有对应的OrderDetailVo，则创建一个新的实例
                return OrderDetailVo.builder()
                        .orderNo(detail.getOrderNo())
                        .receiveName(orderInfo.getReceiveName())
                        .products(new ArrayList<>()) // 初始化商品列表
                        .totalPrice(BigDecimal.ZERO) // 初始化总价为0
                        .statusDesc(detail.getStatusDesc())
                        .id(detail.getId())
                        .createTime(detail.getCreateTime())
                        .build();
            });

            // 添加或更新商品信息到对应的OrderDetailVo中
            Product product = productMapper.getProduct(detail.getProductId());
            vo.getProducts().add(ProductInOrder.builder()
                    .productName(product.getName())
                    .productImage(product.getMainImage())
                    .productPrice(product.getPrice())
                    .productNum(detail.getQuantity())
                    .build());

            // 累加总价
            vo.setTotalPrice(vo.getTotalPrice().add(detail.getCurrentUnitPrice().multiply(new BigDecimal(detail.getQuantity()))));
        }

        // 将Map中的值转换为列表
        List<OrderDetailVo> vos = new ArrayList<>(orderVoMap.values());
        OrderListVo orderListVo = OrderListVo.builder()
                .total((int) pageInfo.getTotal())
                .current(pageInfo.getPageNum())
                .size(pageInfo.getPageSize())
                .pages((int)(pageInfo.getTotal() % pageInfo.getPageSize() == 0 ? pageInfo.getTotal() / pageInfo.getPageSize() : pageInfo.getTotal() / pageInfo.getPageSize() + 1))
                .records(vos)
                .build();
        return FwResult.ok(orderListVo);
    }


//    @Override
//    public FwResult getOrderPage(PageDto pageDto) {
//        Long userId = Long.valueOf(redisUtils.get("userId"));
//        PageHelper.startPage(pageDto.getCurrent(), pageDto.getSize());
//        // 查询订单详情
//        List<OrderDetail> details = orderMapper.getOrderPage(userId);
//
//        if (details.isEmpty()) {
//            return FwResult.failedMsg("没有订单");
//        }
//
//        Map<String, OrderDetailVo> orderVoMap = new HashMap<>();
//
//        // 遍历每个订单详情，构建订单VO
//        for (OrderDetail detail : details) {
//            // 使用订单号作为键，避免重复添加
//            OrderDetailVo vo = orderVoMap.computeIfAbsent(detail.getOrderNo(), k -> {
//                // 获取订单信息
//                OrderInfo orderInfo = orderMapper.getOrderInfoByOrderNo(userId, detail.getOrderNo()).get(0);
//                return OrderDetailVo.builder()
//                        .orderNo(detail.getOrderNo())
//                        .receiveName(orderInfo.getReceiveName())
//                        .products(new ArrayList<>())
//                        .totalPrice(BigDecimal.ZERO)
//                        .statusDesc(orderInfo.getStatusDesc())
//                        .id(orderInfo.getId())
//                        .createTime(orderInfo.getCreateTime())
//                        .build();
//            });
//
//            // 添加商品信息到对应的OrderDetailVo
//            Product product = productMapper.getProduct(detail.getProductId());
//            vo.getProducts().add(ProductInOrder.builder()
//                    .productName(product.getName())
//                    .productImage(product.getMainImage())
//                    .productPrice(product.getPrice())
//                    .productNum(detail.getQuantity())
//                    .productTotalPrice(detail.getCurrentUnitPrice().multiply(new BigDecimal(detail.getQuantity())))
//                    .build());
//
//            // 累加总价
//            vo.setTotalPrice(vo.getTotalPrice().add(detail.getCurrentUnitPrice().multiply(new BigDecimal(detail.getQuantity()))));
//        }
//
//        List<OrderDetailVo> vos = new ArrayList<>(orderVoMap.values());
//
//        // 返回分页信息
//        PageInfo<OrderDetail> pageInfo = new PageInfo<>(details);
//        OrderListVo orderListVo = OrderListVo.builder()
//                .total((int) pageInfo.getTotal())
//                .current(pageInfo.getPageNum())
//                .size(pageInfo.getPageSize())
//                .pages((int) (pageInfo.getTotal() % pageInfo.getPageSize() == 0 ? pageInfo.getTotal() / pageInfo.getPageSize() : pageInfo.getTotal() / pageInfo.getPageSize() + 1))
//                .records(vos)
//                .build();
//
//        return FwResult.ok(orderListVo);
//    }



    @Override
    @Transactional
    public FwResult createOrder(OrderCreateDto list) {
        Long userId = Long.valueOf(redisUtils.get("userId"));
        //       随机生成订单号
        String orderNo = System.currentTimeMillis()+"";
        for (ProductInOrderDto orderCreateDto : list.getProducts()) {
            Product product = productMapper.getProduct(orderCreateDto.getProductId());
            if (product==null){
                throw new DataOrCheckException("数据有误或校验失败");
            }
            BigDecimal totalPrice = product.getPrice().multiply(new BigDecimal(orderCreateDto.getProductNum()));

            OrderInfo orderInfo = OrderInfo.builder()
                    .userId(userId)
                    .orderNo(orderNo)
                    .payment(totalPrice)
                    .paymentType(0)
                    .paymentTypeDesc("未支付")
                    .status(false)
                    .statusDesc("待支付")
                    .build();

            log.info("订单信息：{}",orderInfo);
            orderMapper.createOrderInfo(orderInfo);
            OrderDetail orderDetail = OrderDetail.builder()
                    .userId(Long.valueOf(redisUtils.get("userId")))
                    .orderNo(orderNo)
                    .orderDetailNo(orderNo)
                    .productId(product.getId())
                    .productName(product.getName())
                    .productMainImage(product.getMainImage())
                    .currentUnitPrice(product.getPrice())
                    .quantity(orderCreateDto.getProductNum())
                    .totalPrice(totalPrice)
                    .status(false)
                    .statusDesc("待支付")
                    .build();
            log.info("订单详情：{}",orderDetail);

            orderMapper.createOrderDetail(orderDetail);
        }


        return FwResult.ok(orderNo);
    }

//    @Override
//    @Transactional
//    public FwResult createOrder(OrderCreateDto list) {
//        Long userId = Long.valueOf(redisUtils.get("userId"));
//        // 随机生成订单号
//        String orderNo = System.currentTimeMillis() + "";
//
//        // 遍历创建订单详情
//        for (ProductInOrderDto orderCreateDto : list.getProducts()) {
//            Product product = productMapper.getProduct(orderCreateDto.getProductId());
//            if (product == null) {
//                throw new DataOrCheckException("数据有误或校验失败");
//            }
//            BigDecimal totalPrice = product.getPrice().multiply(new BigDecimal(orderCreateDto.getProductNum()));
//
//            // 创建订单信息
//            OrderInfo orderInfo = OrderInfo.builder()
//                    .userId(userId)
//                    .orderNo(orderNo)
//                    .payment(totalPrice)
//                    .paymentType(0)
//                    .paymentTypeDesc("未支付")
//                    .status(false)
//                    .statusDesc("待支付")
//                    .build();
//
//            log.info("订单信息：{}", orderInfo);
//            orderMapper.createOrderInfo(orderInfo);
//
//            // 创建订单详情
//            OrderDetail orderDetail = OrderDetail.builder()
//                    .userId(userId)
//                    .orderNo(orderNo)
//                    .orderDetailNo(orderNo)  // 确保 order_detail_no 被赋值
//                    .productId(product.getId())
//                    .productName(product.getName())
//                    .productMainImage(product.getMainImage())
//                    .currentUnitPrice(product.getPrice())
//                    .quantity(orderCreateDto.getProductNum())
//                    .totalPrice(totalPrice)
//                    .status(false)
//                    .statusDesc("待支付")
//                    .build();
//
//            log.info("订单详情：{}", orderDetail);
//
//            // 创建订单详情
//            orderMapper.createOrderDetail(orderDetail);
//        }
//
//        return FwResult.ok(orderNo);  // 返回订单号
//    }



    @Override
    public FwResult completeOrder(OrderCompleteDto orderCompleteDto) {
        try {
            String orderNo = orderCompleteDto.getOrderNo();
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return FwResult.failedMsg("订单号不能为空");
            }

            Long userId = Optional.ofNullable(redisUtils.get("userId"))
                    .filter(str -> !str.isEmpty())
                    .map(Long::valueOf)
                    .orElseThrow(() -> new RuntimeException("用户ID不存在"));

            Long addressId = orderCompleteDto.getAddressId();
            Address address = addressMapper.getAddressByAddressId(userId, addressId);
            log.info("地址:{}", address);
            if (address == null) {
                return FwResult.failedMsg("地址信息不存在");
            }

            OrderInfo orderInfo = buildOrderInfo(orderNo, true, "待支付", address);
            OrderDetail orderDetail = buildOrderDetail(orderNo, true, "待支付");

            if (updateOrder(orderInfo, orderDetail)) {
                return FwResult.okMsg("订单信息已完善");
            } else {
                return FwResult.failedMsg("订单信息完善失败");
            }
        } catch (Exception e) {
            // 异常处理逻辑，如记录日志等
            return FwResult.failedMsg("操作失败，系统异常");
        }
    }

    private boolean updateOrder(OrderInfo orderInfo, OrderDetail orderDetail) {
        // 使用事务保证更新操作的原子性
        boolean orderInfoUpdated = orderMapper.updateOrderInfo(orderInfo) >= 1;
        boolean orderDetailUpdated = orderMapper.updateOrderDetail(orderDetail) >= 1;
        return orderInfoUpdated && orderDetailUpdated;
    }

    @Override
    public FwResult cancelOrder(String orderNo) {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            return FwResult.failedMsg("订单号不能为空");
        }

        OrderInfo orderInfo = buildOrderInfo(orderNo, false, "已取消");
        OrderDetail orderDetail = buildOrderDetail(orderNo, false, "已取消", LocalDateTime.now());

        if (updateOrder(orderInfo, orderDetail)) {
            return FwResult.okMsg("取消成功");
        } else {
            return FwResult.failedMsg("取消失败");
        }
    }

    @Override
    public FwResult getPayInfo(String orderNo){
        Long userId = Long.valueOf(redisUtils.get("userId"));
        List<OrderInfo> infos = orderMapper.getOrderInfoByOrderNo(userId, orderNo);
        List<OrderDetail> details = orderMapper.getOrderByOrderNo(userId, orderNo);
        BigDecimal payMoney = details.stream().map(OrderDetail::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (infos.isEmpty() || details.isEmpty()){
            return FwResult.failedMsg("订单不存在");
        }
        OrderInfo orderInfo = infos.get(0);
        List<ProductInOrder> products = new ArrayList<>();
        for (int i = 0; i < infos.size(); i++) {
            ProductInOrder productInOrder = ProductInOrder.builder()
                    .productName(details.get(i).getProductName())
                    .productImage(details.get(i).getProductMainImage())
                    .productPrice(details.get(i).getCurrentUnitPrice())
                    .productNum(details.get(i).getQuantity())
                    .build();
            products.add(productInOrder);
        }
        String address = orderInfo.getProvince()+orderInfo.getCity()+orderInfo.getArea()+orderInfo.getStreet();
        PayInfoVo payInfoVo = PayInfoVo.builder()
                .payMoney(payMoney)
                .orderNo(orderInfo.getOrderNo())
                .payMoney(orderInfo.getPayment())
                .address(address)
                .receiveName(orderInfo.getReceiveName())
                .receivePhone(orderInfo.getReceivePhone())
                .products(products)
                .build();

        return FwResult.ok(payInfoVo);
    }

    @Override
    @Transactional
    public FwResult payOrder(PayOrderDto payOrderDto) {


        String orderNo = payOrderDto.getOrderNo();
        User userInfo=null;
        BigDecimal totalPrice=BigDecimal.ZERO;
        List<OrderDetail> orderDetai1l=orderMapper.selectList(orderNo);
        for (OrderDetail orderDetail : orderDetai1l) {
            totalPrice=totalPrice.add(orderDetail.getTotalPrice());
        }
        if (payOrderDto.getPayType()==3){
            userInfo = userMapper.getUserById(Long.valueOf(redisUtils.get("userId")));
            if (userInfo.getBalance().compareTo(totalPrice)<0){
                return FwResult.failedMsg("余额不足");
            }
        }
        Integer paymentType = payOrderDto.getPayType();
        String paymentTpeDesc = "";
        String statusDesc = "";
        if (paymentType==null){
            return FwResult.failedMsg("支付类型不能为空");
        }else if (paymentType==1){
            paymentTpeDesc = "微信支付";
        }else if (paymentType==2){
            paymentTpeDesc = "支付宝";
        }else if (paymentType==3){
            paymentTpeDesc = "余额支付";
        }
        if (payOrderDto.getIsPay()){
            statusDesc = "已支付";
        }else{
            statusDesc = "待支付";
        }

        if (orderNo!=null){
            OrderInfo orderInfo = OrderInfo.builder()
                    .orderNo(orderNo)
                    .status(true)
                    .statusDesc(statusDesc)
                    .paymentType(paymentType)
                    .paymentTypeDesc(paymentTpeDesc)
                    .paymentTime(new Date())
                    .build();
            Integer x = orderMapper.updateOrderInfo(orderInfo);

            OrderDetail orderDetail = OrderDetail.builder()
                    .orderNo(orderNo)
                    .status(true)
                    .statusDesc(statusDesc)
                    .build();
            Integer y =orderMapper.updateOrderDetail(orderDetail);

            if (x>0 && y>0&&!statusDesc.equals("未支付")){
                if (payOrderDto.getPayType()==3){
                    userInfo.setBalance(userInfo.getBalance().subtract (totalPrice));
                    userMapper.updateUser(userInfo);
                }
                return FwResult.okMsg("支付成功");
            }
        }
        return FwResult.failedMsg("支付失败");
    }

    private OrderInfo buildOrderInfo(String orderNo, boolean status, String statusDesc, Address address) {
        return OrderInfo.builder()
                .orderNo(orderNo)
                .status(status)
                .statusDesc(statusDesc)
                .addressId(address.getAddressId())
                .postalCode(address.getPostalCode())
                .receivePhone(address.getReceivePhone())
                .province(address.getProvince())
                .city(address.getCity())
                .area(address.getArea())
                .street(address.getStreet())
                .receiveName(address.getReceiveName())
                .build();
    }

    private OrderInfo buildOrderInfo(String orderNo, boolean status, String statusDesc) {
        return OrderInfo.builder()
                .orderNo(orderNo)
                .status(status)
                .statusDesc(statusDesc)
                .build();
    }

    private OrderDetail buildOrderDetail(String orderNo, boolean status, String statusDesc, LocalDateTime cancelTime) {
        return OrderDetail.builder()
                .orderNo(orderNo)
                .status(status)
                .statusDesc(statusDesc)
                .cancelTime(cancelTime)
                .build();
    }

    private OrderDetail buildOrderDetail(String orderNo, boolean status, String statusDesc) {
        return OrderDetail.builder()
                .orderNo(orderNo)
                .status(status)
                .statusDesc(statusDesc)
                .build();
    }
}
